<template>
  <el-container>
    <el-aside width="200px" style="border-right: 1px solid #e4e7ed">
      <el-menu
        default-active="1"
        class="el-menu-vertical-demo"
        @select="handleMenuSelect"
        style="overflow-x: none; overflow-y: none"
      >
        <el-menu-item index="1">
          <i class="el-icon-phone" slot="icon"></i>
          <span slot="title">更换手机号</span>
        </el-menu-item>
        <el-menu-item index="2">
          <i class="el-icon-lock" slot="icon"></i>
          <span slot="title">修改密码</span>
        </el-menu-item>
        <el-menu-item index="3">
          <i class="el-icon-comment" slot="icon"></i>
          <span slot="title">设置招呼语</span>
        </el-menu-item>
      </el-menu>
    </el-aside>
    <el-main class="main">
      <div class="steps-container">
        <div class="title">
          <h2>账号与安全中心</h2>
        </div>

        <el-steps
          v-if="activeMenu !== '3'"
          :space="300"
          :active="currentStep"
          finish-status="success"
          align-center
        >
          <el-step :title="stepTitles[0]"></el-step>
          <el-step :title="stepTitles[1]"></el-step>
          <el-step :title="stepTitles[2]"></el-step>
        </el-steps>

        <!-- 步骤内容区域 -->
        <div class="step-content">
          <!-- 更换手机号相关表单 -->
          <el-form
            v-show="activeMenu === '1' && currentStep === 0"
            :model="phoneForm"
            ref="passwordForm"
            label-width="100px"
          >
            <el-form-item
              label="密码:"
              prop="password"
              :rules="[
                { required: true, message: '请输入当前密码', trigger: 'blur' },
              ]"
            >
              <el-input
                type="password"
                v-model="phoneForm.password"
                placeholder="请输入当前密码"
                show-password
              ></el-input>
            </el-form-item>
          </el-form>

          <el-form
            v-show="activeMenu === '1' && currentStep === 1"
            :model="phoneForm"
            ref="oldPhoneForm"
            label-width="100px"
          >
            <el-form-item
              label="旧手机号:"
              prop="oldPhone"
              :rules="[
                { required: true, message: '请输入旧手机号', trigger: 'blur' },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入正确的手机号格式',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                v-model="phoneForm.oldPhone"
                placeholder="请输入旧手机号"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-form>

          <el-form
            v-if="activeMenu === '1' && currentStep === 2"
            :model="phoneForm"
            ref="newPhoneForm"
            label-width="100px"
          >
            <el-form-item
              label="新手机号:"
              prop="newPhone"
              :rules="[
                { required: true, message: '请输入新手机号', trigger: 'blur' },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入正确的手机号格式',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                v-model="phoneForm.newPhone"
                placeholder="请输入新手机号"
                maxlength="11"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="新手机号:"
              prop="confirmPhone"
              :rules="[
                { required: true, message: '请确认新手机号', trigger: 'blur' },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入正确的手机号格式',
                  trigger: 'blur',
                },
                { validator: validatePhoneEquals, trigger: 'blur' },
              ]"
            >
              <el-input
                v-model="phoneForm.confirmPhone"
                placeholder="请确认新手机号"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-form>

          <!-- 修改密码相关表单 -->
          <el-form
            v-if="activeMenu === '2' && currentStep === 0"
            :model="passwordForm"
            ref="phoneForm"
            label-width="100px"
          >
            <el-form-item
              label="手机号:"
              prop="phone"
              :rules="[
                { required: true, message: '请输入手机号', trigger: 'blur' },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入正确的手机号格式',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                v-model="passwordForm.phone"
                placeholder="请输入手机号"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-form>

          <el-form
            v-if="activeMenu === '2' && currentStep === 1"
            :model="passwordForm"
            ref="oldPwdForm"
            label-width="100px"
          >
            <el-form-item
              label="旧密码:"
              prop="oldPassword"
              :rules="[
                { required: true, message: '请输入旧密码', trigger: 'blur' },
                { min: 4, message: '密码长度不能少于4位', trigger: 'blur' },
              ]"
            >
              <el-input
                type="password"
                v-model="passwordForm.oldPassword"
                placeholder="请输入当前密码"
                show-password
              ></el-input>
            </el-form-item>
          </el-form>

          <el-form
            v-if="activeMenu === '2' && currentStep === 2"
            :model="passwordForm"
            ref="newPwdForm"
            label-width="100px"
          >
            <el-form-item
              label="新密码"
              prop="newPassword"
              :rules="[
                { required: true, message: '请输入新密码', trigger: 'blur' },
                { min: 4, message: '密码长度不能少4位', trigger: 'blur' },
              ]"
            >
              <el-input
                type="password"
                v-model="passwordForm.newPassword"
                placeholder="请输入新密码"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item
              label="新密码:"
              prop="confirmPassword"
              :rules="[
                { required: true, message: '请确认新密码', trigger: 'blur' },
                { min: 4, message: '密码长度不能少于4位', trigger: 'blur' },
                { validator: validatePasswordEquals, trigger: 'blur' },
              ]"
            >
              <el-input
                type="password"
                v-model="passwordForm.confirmPassword"
                placeholder="请确认新密码"
                show-password
              ></el-input>
            </el-form-item>
          </el-form>
        </div>

        <!-- 操作按钮：仅在选择手机号/密码修改时显示 -->
        <div class="button-group" v-if="activeMenu !== '3'">
          <el-button @click="prevStep" :disabled="currentStep === 0">
            上一步
          </el-button>
          <el-button type="primary" @click="nextStep" v-if="currentStep < 2">
            下一步
          </el-button>
          <el-button
            type="primary"
            @click="submitForm"
            v-if="currentStep === 2"
          >
            确认提交
          </el-button>
        </div>

        <!-- 招呼语设置表单：独立模块，无步骤条和步骤按钮 -->
        <div v-if="activeMenu === '3'" class="greeting-container">
          <el-form :model="greetingForm" ref="greetingForm" label-width="100px">
            <el-form-item
              label="选择话术:"
              prop="selectedGreeting"
              :rules="[
                {
                  required: true,
                  message: '请选择或输入招呼语',
                  trigger: 'blur',
                },
              ]"
            >
              <el-select
                v-model="greetingForm.selectedGreeting"
                placeholder="选择预设话术或自定义"
                clearable
                @change="handleGreetingChange"
                style="width: 100%"
              >
                <el-option label="自定义输入" value="custom"></el-option>
                <el-option
                  v-for="(item, index) in greetingOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 自定义输入框 -->
            <el-form-item
              v-if="greetingForm.selectedGreeting === 'custom'"
              label="自定义话术:"
              prop="customGreeting"
              :rules="[
                {
                  required: true,
                  message: '请输入自定义招呼语',
                  trigger: 'blur',
                },
                { max: 100, message: '话术长度不能超过100字', trigger: 'blur' },
              ]"
            >
              <el-input
                v-model="greetingForm.customGreeting"
                placeholder="请输入自定义招呼语"
                type="textarea"
                rows="3"
                maxlength="100"
                show-word-limit
              ></el-input>
            </el-form-item>

            <!-- 招呼语专用保存按钮 -->
            <el-form-item>
              <el-button type="primary" @click="saveGreeting">
                保存招呼语
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { resetPassword, resetPhone } from "@/api/recuriter/register";

export default {
  data() {
    return {
      greetingForm: {
        selectedGreeting: "",
        customGreeting: "",
      },
      greetingOptions: [
        "您好！看到您的简历很匹配我们的岗位，方便聊聊吗？",
        "我们正在招聘岗位，您感兴趣吗？",
        "您好～ 您的过往经历很符合我们的需求，约个面试详谈？",
        "看到您在专业领域很专业，我们团队正在招相关人才，聊聊？",
        "您好！我司急招，双休+五险一金，期待您的加入～",
        "您的简历很亮眼，我们的岗位挺适合您，有空沟通下吗？",
        "我们在招该岗位，弹性工作+年终分红，方便发您详细JD吗？",
        "您好～ 注意到您正在找工作，我们的岗位匹配度很高哦！",
        "看到您很有经验，我们团队刚好有个合适的机会，聊聊？",
        "您好！我司正在扩张，岗位急缺人才，期待您的投递～",
      ],

      activeMenu: "1",
      currentStep: 0,
      stepTitles: ["输入密码", "输入旧手机号", "输入新手机号"],
      phoneForm: {
        password: "",
        oldPhone: "",
        newPhone: "",
        confirmPhone: "",
        verifyCode: "",
      },
      passwordForm: {
        phone: "",
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
        verifyCode: "",
      },
    };
  },
  created() {
    this.greetingForm.selectedGreeting = this.$store.state.recruiter.Greeting;
  },
  methods: {
    // 招呼语相关方法
    handleGreetingChange(val) {
      if (val !== "custom") {
        this.greetingForm.customGreeting = "";
      }
    },
    saveGreeting() {
      this.$refs.greetingForm.validate((valid) => {
        if (valid) {
          const finalGreeting =
            this.greetingForm.selectedGreeting === "custom"
              ? this.greetingForm.customGreeting
              : this.greetingForm.selectedGreeting;

          this.$store.commit("recruiter/SET_GREETING", finalGreeting);
          this.$message.success("设置成功");
        }
      });
    },

    handleMenuSelect(key) {
      this.activeMenu = key;
      this.currentStep = 0;

      if (key === "1") {
        this.stepTitles = ["输入密码", "输入旧手机号", "输入新手机号"];
      } else if (key === "2") {
        this.stepTitles = ["输入手机号", "输入旧密码", "输入新密码"];
      }
    },
    prevStep() {
      if (this.currentStep > 0) {
        this.currentStep--;
      }
    },
    nextStep() {
      let formName = "";
      if (this.activeMenu === "1") {
        formName = this.currentStep === 0 ? "passwordForm" : "oldPhoneForm";
      } else {
        formName = this.currentStep === 0 ? "phoneForm" : "oldPwdForm";
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.currentStep++;
        }
      });
    },
    submitForm() {
      let formName = this.activeMenu === "1" ? "newPhoneForm" : "newPwdForm";
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return;
        try {
          if (formName === "newPhoneForm") {
            const { oldPhone, newPhone, password } = this.phoneForm;
            await resetPhone(oldPhone, newPhone, password);
          } else {
            const { phone, oldPassword, newPassword } = this.passwordForm;
            await resetPassword(phone, oldPassword, newPassword);
          }
          this.$message.success("修改成功！请重新登录");
          this.$router.replace("/login");
        } catch (error) {
          this.$message.error("修改失败,请稍后重试");
        } finally {
          this.resetForms();
          this.currentStep = 0;
        }
      });
    },
    validatePhoneEquals(rule, value, callback) {
      if (value !== this.phoneForm.newPhone) {
        callback(new Error("两次输入的手机号不一致"));
      } else {
        callback();
      }
    },
    validatePasswordEquals(rule, value, callback) {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    },
    resetForms() {
      this.phoneForm = {
        password: "",
        oldPhone: "",
        newPhone: "",
        confirmPhone: "",
        verifyCode: "",
      };
      this.passwordForm = {
        phone: "",
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
        verifyCode: "",
      };
    },
  },
};
</script>

<style scoped>
.steps-container {
  max-width: 800px;
}

.step-content {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  margin: 20px 0;
}

.button-group {
  text-align: right;
  margin-top: 20px;
}

.button-group .el-button {
  margin-left: 10px;
}

/* 招呼语样式 */
.greeting-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  margin-top: 20px;
}
</style>